// python -m http.server 8000

// 模拟多个策略收益数据
const strategyPerformanceData = {
    'strategy_1': [
        { date: '2023-01-01', value: 0 },
        { date: '2023-01-02', value: 1.2 },
        { date: '2023-01-03', value: 2.5 },
        { date: '2023-01-04', value: 1.8 },
        { date: '2023-01-05', value: 3.2 },
        { date: '2023-01-06', value: 4.1 },
        { date: '2023-01-07', value: 3.7 }
    ],
    'strategy_2': [
        { date: '2023-01-01', value: 0 },
        { date: '2023-01-02', value: 0.8 },
        { date: '2023-01-03', value: 1.5 },
        { date: '2023-01-04', value: 2.1 },
        { date: '2023-01-05', value: 1.9 },
        { date: '2023-01-06', value: 2.6 },
        { date: '2023-01-07', value: 3.2 }
    ],
    'strategy_3': [
        { date: '2023-01-01', value: 0 },
        { date: '2023-01-02', value: -0.5 },
        { date: '2023-01-03', value: 0.2 },
        { date: '2023-01-04', value: 1.1 },
        { date: '2023-01-05', value: 0.8 },
        { date: '2023-01-06', value: 1.4 },
        { date: '2023-01-07', value: 1.9 }
    ]
};

import { renderMarketTable, renderStockTable, updateAccountInfo, renderPortfolioTable, executeTrade } from './market.js'
import { renderStrategyList, renderCustomFieldsList, renderPreviewTable, setupFieldManagementEvents, setupStrategyEditorEvents } from './strategy.js'

document.addEventListener('DOMContentLoaded', () => {
    
    renderMarketTable();    
    renderStockTable();
    updateAccountInfo();
    renderPortfolioTable();
    setupNavigation();
    setupEventListeners();
    
    // 只在策略页面初始化
    const strategyPage = document.getElementById('strategy-page');
    if (strategyPage) {
        renderStrategyList();
        renderCustomFieldsList();
        renderPreviewTable();
        setupFieldManagementEvents();
        setupStrategyEditorEvents();
    }
    
    // 在首页添加策略收益图表
    const dashboardPage = document.getElementById('dashboard-page');
    if (dashboardPage) {
        renderStrategyPerformanceChart();
    }
});

function setupNavigation() {
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        item.addEventListener('click', () => {
            // Remove active class from all items
            navItems.forEach(navItem => {
                navItem.classList.remove('active-nav');
            });
            
            // Add active class to clicked item
            item.classList.add('active-nav');
            
            // Hide all pages
            document.querySelectorAll('.page').forEach(page => {
                page.classList.remove('active');
            });
            
            // Show target page
            const targetPage = item.getAttribute('data-target');
            document.getElementById(targetPage).classList.add('active');
        });
    });
}

// 添加渲染策略收益图表的函数
function renderStrategyPerformanceChart() {
    const chartContainer = document.createElement('div');
    chartContainer.className = 'bg-white rounded-xl shadow-md p-6 mb-6';
    chartContainer.innerHTML = `
        <h2 class="text-xl font-semibold mb-4">策略收益</h2>
        <div id="strategy-charts-container"></div>
    `;
    
    // 插入到账户概览之后
    const accountOverview = document.querySelector('#dashboard-page .bg-white.rounded-xl.shadow-md.p-6.mb-6');
    accountOverview.after(chartContainer);
    
    // 绘制所有策略图表
    drawAllStrategyCharts();
}

// 绘制所有策略收益图表
function drawAllStrategyCharts() {
    const container = document.getElementById('strategy-charts-container');
    if (!container) return;
    
    // 清空容器
    container.innerHTML = '';
    
    // 为每个策略创建图表
    Object.keys(strategyPerformanceData).forEach(strategyId => {
        const chartWrapper = document.createElement('div');
        chartWrapper.className = 'strategy-chart-wrapper mb-6';
        chartWrapper.innerHTML = `
            <div class="flex justify-between items-center mb-2">
                <h3 class="font-medium">策略 ${strategyId.split('_')[1]}</h3>
                <button class="text-blue-500 text-sm view-strategy-detail" data-strategy="${strategyId}">
                    查看详情 <i class="fas fa-arrow-right"></i>
                </button>
            </div>
            <canvas id="strategy-chart-${strategyId}" height="150"></canvas>
        `;
        container.appendChild(chartWrapper);
    });
    
    // 绘制每个图表
    Object.keys(strategyPerformanceData).forEach(strategyId => {
        drawStrategyChart(strategyId);
    });
    
    // 绑定查看详情事件
    document.querySelectorAll('.view-strategy-detail').forEach(button => {
        button.addEventListener('click', function() {
            const strategyId = this.getAttribute('data-strategy');
            showStrategyDetail(strategyId);
        });
    });
}

// 绘制单个策略收益图表
function drawStrategyChart(strategyId) {
    const canvas = document.getElementById(`strategy-chart-${strategyId}`);
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    const chartWidth = canvas.width;
    const chartHeight = canvas.height;
    
    // 清空画布
    ctx.clearRect(0, 0, chartWidth, chartHeight);
    
    const data = strategyPerformanceData[strategyId];
    
    // 设置图表边距
    const margin = { top: 10, right: 10, bottom: 20, left: 40 };
    const width = chartWidth - margin.left - margin.right;
    const height = chartHeight - margin.top - margin.bottom;
    
    // 找到最大值和最小值
    const values = data.map(d => d.value);
    const maxValue = Math.max(...values);
    const minValue = Math.min(...values);
    const valueRange = maxValue - minValue || 1; // 防止除零
    
    // 绘制坐标轴
    ctx.beginPath();
    ctx.strokeStyle = '#ccc';
    ctx.lineWidth = 1;
    
    // Y轴
    ctx.moveTo(margin.left, margin.top);
    ctx.lineTo(margin.left, margin.top + height);
    
    // X轴
    ctx.moveTo(margin.left, margin.top + height);
    ctx.lineTo(margin.left + width, margin.top + height);
    ctx.stroke();
    
    // 绘制网格线和标签
    ctx.fillStyle = '#666';
    ctx.font = '10px Arial';
    ctx.textAlign = 'right';
    
    // Y轴标签和网格线
    const yTicks = 3;
    for (let i = 0; i <= yTicks; i++) {
        const y = margin.top + height - (i / yTicks) * height;
        const value = minValue + (i / yTicks) * valueRange;
        
        // 网格线
        ctx.beginPath();
        ctx.strokeStyle = '#eee';
        ctx.moveTo(margin.left, y);
        ctx.lineTo(margin.left + width, y);
        ctx.stroke();
        
        // 标签
        ctx.fillText(value.toFixed(1) + '%', margin.left - 5, y + 3);
    }
    
    // X轴标签
    ctx.textAlign = 'center';
    const xTicks = Math.min(data.length, 3); // 只显示开始、中间和结束日期
    for (let i = 0; i < xTicks; i++) {
        const dataIndex = i === 0 ? 0 : 
                         i === 1 ? Math.floor(data.length / 2) : 
                         data.length - 1;
        const x = margin.left + (dataIndex / (data.length - 1)) * width;
        ctx.fillText(data[dataIndex].date.substring(5), x, margin.top + height + 15);
    }
    
    // 绘制折线
    ctx.beginPath();
    ctx.strokeStyle = '#3b82f6';
    ctx.lineWidth = 2;
    
    for (let i = 0; i < data.length; i++) {
        const x = margin.left + (i / (data.length - 1)) * width;
        const y = margin.top + height - ((data[i].value - minValue) / valueRange) * height;
        
        if (i === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    }
    ctx.stroke();
    
    // 绘制数据点
    ctx.fillStyle = '#3b82f6';
    for (let i = 0; i < data.length; i++) {
        const x = margin.left + (i / (data.length - 1)) * width;
        const y = margin.top + height - ((data[i].value - minValue) / valueRange) * height;
        
        ctx.beginPath();
        ctx.arc(x, y, 3, 0, Math.PI * 2);
        ctx.fill();
    }
    
    // 显示最终收益值
    const finalValue = data[data.length - 1].value;
    ctx.fillStyle = finalValue >= 0 ? '#ef4444' : '#10b981';
    ctx.font = 'bold 12px Arial';
    ctx.textAlign = 'right';
    ctx.fillText(finalValue.toFixed(2) + '%', chartWidth - 5, 15);
}

// 显示策略详情
function showStrategyDetail(strategyId) {
    const data = strategyPerformanceData[strategyId];
    if (!data) return;
    
    // 创建模态框
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
    modal.innerHTML = `
        <div class="bg-white rounded-xl shadow-lg w-11/12 max-w-2xl max-h-[90vh] overflow-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-xl font-semibold">策略 ${strategyId.split('_')[1]} 详情</h3>
                    <button class="close-modal text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="mb-6">
                    <canvas id="detail-strategy-chart" height="300"></canvas>
                </div>
                <div class="mb-6">
                    <h4 class="font-medium mb-2">收益数据</h4>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">日期</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">收益 (%)</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                ${data.map(item => `
                                    <tr>
                                        <td class="px-4 py-2 whitespace-nowrap">${item.date}</td>
                                        <td class="px-4 py-2 whitespace-nowrap ${item.value >= 0 ? 'text-red-500' : 'text-green-500'}">
                                            ${item.value >= 0 ? '+' : ''}${item.value.toFixed(2)}%
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
                <div>
                    <h4 class="font-medium mb-2">交易详情</h4>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">日期</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">股票代码</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">股票名称</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">操作</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">价格</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">数量</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <!-- 示例交易数据 -->
                                <tr>
                                    <td class="px-4 py-2 whitespace-nowrap">2023-01-02</td>
                                    <td class="px-4 py-2 whitespace-nowrap">600000</td>
                                    <td class="px-4 py-2 whitespace-nowrap">浦发银行</td>
                                    <td class="px-4 py-2 whitespace-nowrap text-green-500">买入</td>
                                    <td class="px-4 py-2 whitespace-nowrap">10.25</td>
                                    <td class="px-4 py-2 whitespace-nowrap">1000</td>
                                </tr>
                                <tr>
                                    <td class="px-4 py-2 whitespace-nowrap">2023-01-04</td>
                                    <td class="px-4 py-2 whitespace-nowrap">600036</td>
                                    <td class="px-4 py-2 whitespace-nowrap">招商银行</td>
                                    <td class="px-4 py-2 whitespace-nowrap text-red-500">卖出</td>
                                    <td class="px-4 py-2 whitespace-nowrap">36.10</td>
                                    <td class="px-4 py-2 whitespace-nowrap">500</td>
                                </tr>
                                <tr>
                                    <td class="px-4 py-2 whitespace-nowrap">2023-01-05</td>
                                    <td class="px-4 py-2 whitespace-nowrap">601318</td>
                                    <td class="px-4 py-2 whitespace-nowrap">中国平安</td>
                                    <td class="px-4 py-2 whitespace-nowrap text-green-500">买入</td>
                                    <td class="px-4 py-2 whitespace-nowrap">47.90</td>
                                    <td class="px-4 py-2 whitespace-nowrap">800</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 绘制详细图表
    setTimeout(() => {
        drawDetailStrategyChart(strategyId);
    }, 100);
    
    // 绑定关闭事件
    modal.querySelector('.close-modal').addEventListener('click', () => {
        document.body.removeChild(modal);
    });
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    });
}

// 绘制详细策略收益图表
function drawDetailStrategyChart(strategyId) {
    const canvas = document.getElementById('detail-strategy-chart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    const chartWidth = canvas.width;
    const chartHeight = canvas.height;
    
    // 清空画布
    ctx.clearRect(0, 0, chartWidth, chartHeight);
    
    const data = strategyPerformanceData[strategyId];
    
    // 设置图表边距
    const margin = { top: 20, right: 20, bottom: 40, left: 60 };
    const width = chartWidth - margin.left - margin.right;
    const height = chartHeight - margin.top - margin.bottom;
    
    // 找到最大值和最小值
    const values = data.map(d => d.value);
    const maxValue = Math.max(...values);
    const minValue = Math.min(...values);
    const valueRange = maxValue - minValue || 1; // 防止除零
    
    // 绘制坐标轴
    ctx.beginPath();
    ctx.strokeStyle = '#ccc';
    ctx.lineWidth = 1;
    
    // Y轴
    ctx.moveTo(margin.left, margin.top);
    ctx.lineTo(margin.left, margin.top + height);
    
    // X轴
    ctx.moveTo(margin.left, margin.top + height);
    ctx.lineTo(margin.left + width, margin.top + height);
    ctx.stroke();
    
    // 绘制网格线和标签
    ctx.fillStyle = '#666';
    ctx.font = '12px Arial';
    ctx.textAlign = 'right';
    
    // Y轴标签和网格线
    const yTicks = 5;
    for (let i = 0; i <= yTicks; i++) {
        const y = margin.top + height - (i / yTicks) * height;
        const value = minValue + (i / yTicks) * valueRange;
        
        // 网格线
        ctx.beginPath();
        ctx.strokeStyle = '#eee';
        ctx.moveTo(margin.left, y);
        ctx.lineTo(margin.left + width, y);
        ctx.stroke();
        
        // 标签
        ctx.fillText(value.toFixed(1) + '%', margin.left - 5, y + 4);
    }
    
    // X轴标签
    ctx.textAlign = 'center';
    const xTicks = Math.min(data.length, 7); // 最多显示7个日期标签
    for (let i = 0; i < data.length; i++) {
        // 只在特定位置显示标签
        if (data.length <= 7 || i % Math.floor(data.length / (xTicks - 1)) === 0 || i === data.length - 1) {
            const x = margin.left + (i / (data.length - 1)) * width;
            ctx.fillText(data[i].date.substring(5), x, margin.top + height + 20);
        }
    }
    
    // 绘制折线
    ctx.beginPath();
    ctx.strokeStyle = '#3b82f6';
    ctx.lineWidth = 2;
    
    for (let i = 0; i < data.length; i++) {
        const x = margin.left + (i / (data.length - 1)) * width;
        const y = margin.top + height - ((data[i].value - minValue) / valueRange) * height;
        
        if (i === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    }
    ctx.stroke();
    
    // 绘制数据点
    ctx.fillStyle = '#3b82f6';
    for (let i = 0; i < data.length; i++) {
        const x = margin.left + (i / (data.length - 1)) * width;
        const y = margin.top + height - ((data[i].value - minValue) / valueRange) * height;
        
        ctx.beginPath();
        ctx.arc(x, y, 4, 0, Math.PI * 2);
        ctx.fill();
    }
}

function setupEventListeners() {
    // 价格类型切换
    const priceType = document.getElementById('price-type');
    if (priceType) {
        priceType.addEventListener('change', (e) => {
            const limitPriceGroup = document.getElementById('limit-price-group');
            if (limitPriceGroup) {
                limitPriceGroup.classList.toggle('hidden', e.target.value !== 'limit');
            }
        });
    }

    // 股票代码自动填充
    document.querySelectorAll('.trade-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const code = e.target.dataset.code;
            const stockCodeInput = document.getElementById('stock-code');
            if (stockCodeInput) {
                stockCodeInput.value = code;
            }
            
            // Switch to trade page
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active-nav');
            });
            const tradePageNavItem = document.querySelector('[data-target="trade-page"]');
            if (tradePageNavItem) {
                tradePageNavItem.classList.add('active-nav');
            }
            
            document.querySelectorAll('.page').forEach(page => {
                page.classList.remove('active');
            });
            const tradePage = document.getElementById('trade-page');
            if (tradePage) {
                tradePage.classList.add('active');
            }
        });
    });

    // 刷新按钮
    const refreshBtn = document.getElementById('refresh-btn');
    if (refreshBtn) {
        refreshBtn.addEventListener('click', () => {
            renderStockTable();
        });
    }

    // 表单提交
    const tradeForm = document.getElementById('trade-form');
    if (tradeForm) {
        tradeForm.addEventListener('submit', (e) => {
            e.preventDefault();
            executeTrade();
        });
    }

    // 新建策略按钮
    const newStrategyBtn = document.getElementById('btn-new-strategy');
    if (newStrategyBtn) {
        newStrategyBtn.addEventListener('click', () => {
            alert('跳转到策略创建页面');
        });
    }
}







